<template>
  <VtsTreeItem :expanded="!branch.isCollapsed">
    <UiTreeItemLabel icon="fa:server" :route="`/host/${branch.data.id}`" @toggle="branch.toggleCollapse()">
      {{ branch.data.name_label }}
      <template #icon>
        <VtsObjectIcon
          v-tooltip="branch.data.power_state"
          type="host"
          size="medium"
          :state="branch.data.power_state.toLocaleLowerCase() as HostState"
        />
      </template>
      <template #addons>
        <VtsIcon v-if="isMaster" v-tooltip="t('master')" name="legacy:primary" size="medium" />
        <UiCounter
          v-tooltip="t('running-vm', runningVmsCount)"
          :value="runningVmsCount"
          accent="brand"
          variant="secondary"
          size="small"
        />
      </template>
    </UiTreeItemLabel>
    <template v-if="branch.hasChildren" #sublist>
      <VtsTreeList>
        <VmTreeList :leaves="branch.children" />
      </VtsTreeList>
    </template>
  </VtsTreeItem>
</template>

<script lang="ts" setup>
import VmTreeList from '@/components/tree/VmTreeList.vue'
import { useXoHostCollection } from '@/remote-resources/use-xo-host-collection.ts'
import { useXoVmCollection } from '@/remote-resources/use-xo-vm-collection.ts'
import type { HostBranch } from '@/types/tree.type'
import type { HostState } from '@core/types/object-icon.type'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
import { vTooltip } from '@core/directives/tooltip.directive'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

const props = defineProps<{
  branch: HostBranch
}>()

const { t } = useI18n()

const { isMasterHost } = useXoHostCollection()
const { runningVms } = useXoVmCollection()

const isMaster = computed(() => isMasterHost(props.branch.data.id))

const runningVmsCount = computed(() =>
  runningVms.value.reduce(
    (vmCount, runningVm) => (runningVm.$container === props.branch.data.id ? vmCount + 1 : vmCount),
    0
  )
)
</script>
